const Mock = require('mockjs')
const url = require('url')

var data = Mock.mock({
    "data|100":[   //意思是data数组中有100条数据
        {  //这个对象是用来写数据模板的
          "id|+1":0,   //初始值是0每次id都+1
          "goodsName":"@ctitle(3, 5)",   //看官网，这个名字是3-5之间的
          "goodsPrice|+1":100,   //这个类似上面的id一个，只是初始值是从100开始的
          "address":"@county(true)",   //这个是地址，@county(true)  对象的属性值都是mock.mock()提供的方法，直接拿过来用就可以了
          "tel":/^1(3|5|7|8|9)\d{9}$/,   //正则写的电话后面1开头，正则不懂自己去学！！！！！！！！！！！很重要
          "goodsImg":"@image('200x100', '#894FC4', '#FFF', 'alley')", // 图片
          "date":'@date("yyyy-MM-dd M:dd:d")',  //时间
          "email":"@email()"  //邮箱
        }
    ]
})

const success = (data) => {
    return {
        code:0,
        data,
        msg:"success"
    }
}

const fail = (msg="error") => {
    return {
        code:1,
        data:"",
        msg:msg
    }
}


const api = [
    {
        url:'/user/userList',
        type:'get',
        res: req => {
            console.log(req)
            return {
                code:0,
                msg:'success',
                data
            }
        }
    },
    {
        url:'/user/login',
        type:'post',
        res: req => {
            if(req.phone == '15716022393' && req.userPsw == '123456'){
                return {
                    code:0,
                    data:{id:'mockId1'},
                    msg:'登陆成功'
                }
            }else{
                return {code:1,msg:'用户名或密码错误'}
            }
        }
    },
    {
        url:'/article/list',
        type:'get',
        res: req => {
            let page = req.page
            console.log(req)
            let data = Mock.mock({
                "data|20":[   //意思是data数组中有100条数据
                    {  //这个对象是用来写数据模板的
                      "id|+1":1,   //初始值是0每次id都+1
                      "auth":"@ctitle(2,4)",
                      "articleName":"@ctitle(3, 15)",   //看官网，这个名字是3-5之间的
                      "phone":/^1\d{10}$/,   //正则写的电话后面1开头，正则不懂自己去学！！！！！！！！！！！很重要
                      "goodsImg":"@image('200x100', '#894FC4', '#FFF', 'alley')", // 图片
                      "date":'@date("yyyy-MM-dd M:dd:d")',  //时间
                      "email":"@email()",  //邮箱
                      "content":"@ctitle(10, 200)"//
                    }
                ]
            })
            return {code:0,data:page>2 ? [] : data.data,msg:'success'}
        }
    }
]

const formatParams = str => {
    if(!str) return {}
    let arr = str.split('&')
    let obj = {}
    if(!arr.length) return {}
    arr.map(item => {
        let s = item.split('=')
        obj[s[0]] = s[1]
    })
    return obj
}

api.map(item => {
    Mock.mock(new RegExp(`/mock${item.url}`),item.type || 'get',req => {
        console.log(req)
        let params = item.type == 'get' ? formatParams(req.url.split("?")[1] ? req.url.split("?")[1] : '') : formatParams(req.body)
        return item.res(params)
    })  
})
